﻿/// <reference path="../../_references.js" />
(function () {
    angular.module('TfsApp').controller('EditTaskController', ['TaskService', '$routeParams', function (taskService, $routeParams) {
        function EditTaskController() {
            this.isEditing = true;
            if ($routeParams.taskId > 0) {
                this.task = taskService.getTaskById($routeParams.taskId);
                this.task = angular.copy(this.task);
            }
            else {
                this.task = taskService.getNewTask();
            }
            
            this.availableStories = taskService.getAvailableUserStories();            
            this.selectedStory = this.getSelectedStory();
            this.isEditing = false;
            this.isShowingStories = false;
        }

        EditTaskController.prototype.getSelectedStory = function () {
            var taskUserStoryId = this.task.userStoryId;
            var story = Enumerable.From(this.availableStories).FirstOrDefault(null, "i => i.id == " + taskUserStoryId);
            return story;
        };

        EditTaskController.prototype.getSelectedStoryTitle = function () {
            var selectedStory = this.getSelectedStory();
            if (selectedStory !== null) {
                return selectedStory.title;
            }

            return '';
        };        

        EditTaskController.prototype.setUserStory = function (story) {
            this.task.userStoryId = story.id;
            this.selectedStory = story;
            this.isShowingStories = false;
        };

        EditTaskController.prototype.showStories = function () {
            this.isShowingStories = true;
        };

        EditTaskController.prototype.hideStories = function () {
            this.isShowingStories = false;
        };

        EditTaskController.prototype.saveTask = function () {
            this.isEditing = false;
            if (this.selectedStory !== null) {
                this.task.userStoryId = this.selectedStory.id;
            }

            taskService.saveTask(this.task);
            window.history.back();
        };

        EditTaskController.prototype.getTitle = function () {
            if (this.isEditing) {
                if (this.task.id === 0) {
                    return "New Task";
                }

                return "(Editing) " + this.task.title;
            }
            
            return this.task.title;
        };

        return new EditTaskController();
    }]);
})();